<?php

namespace App\Model\Job;


use Illuminate\Database\Eloquent\Model;

/**
 * App\Model\Job\Job
 *
 * @property int $id
 * @property int $parent_job_id
 * @property int $uid
 * @property string $path
 * @property string $title
 * @property string $content
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job wherePath($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereContent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereParentJobId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Job\Job whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Job extends Model
{
    function updatePath()
    {
        if ($this->parent_job_id == 0) {
            $newPath = $this->id;
        } else {
            /**
             * @var Job $parentJob
             */
            $parentJob = Job::findOrFail($this->parent_job_id);
            $newPath = $parentJob->path . '/' . $this->id;
        }
        if (empty($this->path)) {
            $this->path = $newPath;
            $this->save();
        } else {
            //查找所有子类
            $jobs = Job::query()->where('path','like', $this->path . '%')->get();
            $oldPath = $this->path;
            $jobs->map(function ($job) use ($oldPath, $newPath) {
                /**
                 * @var Job $job
                 */
                $job->path = str_replace($oldPath, $newPath, $job->path);
                $job->save();
            });
        }


    }

    public function patentJob()
    {
        return $this->hasOne(Job::class, 'id', 'parent_job_id');
    }
}